﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.PlatformAbstractions;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;
using Org.BouncyCastle.Ocsp;
using DeMeng.Common.Config;
using DeMeng.Common.Extensions;
using DeMeng.Common.Utilities;
using DeMeng.Models;
using DeMeng.Models.Models.UserInfo;
using DeMeng.Models.Swagger;
using DeMeng.Models.ViewModels.UserInfo;
using DeMeng.Services.Domain;

namespace DeMeng.Api.Controllers
{
    /// <summary>
    /// 文件上传
    /// </summary>
    [ApiExplorerSettings(GroupName = Grouping.V1)]
    [Route("Common/[controller]")]
    [ApiController]
    public class UploadController : ControllerBase
    {
        private readonly IHttpClientFactory _httpClient;
        private readonly IUserInfoServices _userInfoServices;
        public UploadController(IHttpClientFactory httpClient, IUserInfoServices userInfoServices)
        {
            _httpClient = httpClient;
            _userInfoServices = userInfoServices;
        }

        #region 图片上传
        /// <summary>
        /// 图片上传
        /// </summary>
        /// <returns></returns>
        [HttpPost(nameof(UploadImage))]
        public async Task<ResponseModel> UploadImage()
        {
            var fileSize = Convert.ToInt32(ManagerConfig.GetManagerConfig("uploadFile:fileSize"));
            if (Request.Form.Files.Count == 0)
                return ResponseModel.Error("请选择文件", new { Parameter = GetParameter(Request.Form) });
            var allowType = new string[] { "image/jpg", "image/png", "image/jpeg" };
            if (!Request.Form.Files.Any(c => allowType.Contains(c.ContentType)))
                return ResponseModel.Error("文件格式不正确", new { Parameter = GetParameter(Request.Form) });
            if (Request.Form.Files.Count > 1)
                return ResponseModel.Error("只能上传单个文件", new { Parameter = GetParameter(Request.Form) });
            var file = Request.Form.Files[0];
            if (file.Length > fileSize * 1024 * 1024 * 8)
                return ResponseModel.Error("文件过大", new { Parameter = GetParameter(Request.Form) });
            try
            {
                var fileName = Guid.NewGuid().ToString().Replace("-", "") + Path.GetExtension(file.FileName);//文件名称
                var uploadPath = Path.Combine("wwwroot/files", DateTime.Now.ToString("yyyyMMdd"));
                var path = Path.Combine(PlatformServices.Default.Application.ApplicationBasePath, uploadPath);
                var filepath = Path.Combine(path, fileName);
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                await using (var stream = new FileStream(filepath, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                {
                    await file.CopyToAsync(stream);
                }
                return ResponseModel.Success(new { Url = WebConfig.WebSiteUrl + "/" + Path.Combine(uploadPath.Replace("wwwroot/", string.Empty), fileName).Replace('\\', '/'), Parameter = GetParameter(Request.Form) });
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("UploadImage", ex);
                throw new ApiException("上传失败");
            }
        }

        #endregion 


        #region 视频上传
        /// <summary>
        /// 视频上传
        /// </summary>
        /// <returns></returns>
        [HttpPost(nameof(UploadVideo))]
        public async Task<ResponseModel> UploadVideo()
        {
            var fileSize = Convert.ToInt32(ManagerConfig.GetManagerConfig("uploadFile:fileSize"));
            if (Request.Form.Files.Count == 0)
                throw new ApiException("请选择文件");
            var allowType = new string[] { "video/avi", "video/mp4", "video/mkv", "video/wmv" };
            if (!Request.Form.Files.Any(c => allowType.Contains(c.ContentType.ToLower())))
                throw new ApiException("文件格式不正确！");
            if (Request.Form.Files.Count > 1)
                throw new ApiException("只能上传单个文件！");
            var file = Request.Form.Files[0];
            if (file.Length > fileSize * 1024 * 1024 * 8)
                throw new ApiException("文件过大");
            try
            {
                var fileName = Guid.NewGuid().ToString().Replace("-", "") + Path.GetExtension(file.FileName);//文件名称
                var uploadPath = Path.Combine("wwwroot/files", DateTime.Now.ToString("yyyyMMdd"));
                var path = Path.Combine(PlatformServices.Default.Application.ApplicationBasePath, uploadPath);
                var filepath = Path.Combine(path, fileName);
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                await using (var stream = new FileStream(filepath, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                {
                    await file.CopyToAsync(stream);
                }

                return ResponseModel.Success(new { Url = WebConfig.WebSiteUrl + "/" + Path.Combine(uploadPath.Replace("wwwroot/", string.Empty), fileName).Replace('\\', '/').Replace("/wwwroot", string.Empty), Parameter = GetParameter(Request.Form) });
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("UploadVideo", ex);
                throw new ApiException("上传失败");
            }
        }

        #endregion 


        #region 文件上传
        /// <summary>
        /// 文件上传
        /// </summary>
        /// <returns></returns>
        [HttpPost(nameof(UploadFile))]
        [RequestFormLimits(ValueCountLimit = int.MaxValue)]
        public async Task<ResponseModel> UploadFile()
        {
            var fileSize = Convert.ToInt32(ManagerConfig.GetManagerConfig("uploadFile:fileSize"));
            //Request.Body.Seek(0, SeekOrigin.Begin);
            if (Request.Form.Files.Count == 0)
                throw new ApiException("请选择文件");
            if (Request.Form.Files.Count > 1)
                throw new ApiException("只能上传单个文件！");
            var file = Request.Form.Files[0];
            if (file.Length > fileSize * 1024 * 1024 * 8)
                throw new ApiException("文件过大");
            try
            {
                var fileName = Guid.NewGuid().ToString().Replace("-", "") + Path.GetExtension(file.FileName);//文件名称
                var uploadPath = Path.Combine("wwwroot/files", DateTime.Now.ToString("yyyyMMdd"));
                var path = Path.Combine(PlatformServices.Default.Application.ApplicationBasePath, uploadPath);
                var filepath = Path.Combine(path, fileName);
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                await using (var stream = new FileStream(filepath, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                {
                    await file.CopyToAsync(stream);
                }
                return ResponseModel.Success(new { Url = WebConfig.WebSiteUrl + "/" + Path.Combine(uploadPath.Replace("wwwroot/", string.Empty), fileName).Replace('\\', '/').Replace("/wwwroot", string.Empty), Parameter = GetParameter(Request.Form) });
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("UploadVideo", ex);
                throw new ApiException("上传失败");
            }
        }
        #endregion
          

        private async Task<string> GetData(byte[] bytes, string fileName)
        {
            //设置请求的路径
            var url = WebConfig.ResumeParseUrl;// "https://www.souqiantu.com:9080/resume/parse_zyhl_test";
            //使用注入的httpclientfactory获取client
            var client = _httpClient.CreateClient();
            //设置请求头
            //           （post提交）（publicKey = MD5（‘秘钥’ + “时间戳”）， 需要约定一个秘钥）
            //1.MultipartFile myfile
            //   2.String publicKey
            //   3.Long timestamp
            //string timeStamp = WxPayApi.GenerateTimeStamp();

            //client.DefaultRequestHeaders.Add("accessToken", model.accesstoken);
            //client.DefaultRequestHeaders.Add("appId", model.appid);
            //client.DefaultRequestHeaders.Add("appId", model.devicekey);
            client.BaseAddress = new Uri(url);
            ByteArrayContent fileContent = new ByteArrayContent(bytes);
            fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { Name = "myfile", FileName = fileName };
            MultipartFormDataContent content = new MultipartFormDataContent();
            content.Add(fileContent);

            //设置请求体中的内容，并以post的方式请求
            var response = await client.PostAsync(url, content);
            //获取请求到数据，并转化为字符串
            var result = response.Content.ReadAsStringAsync().Result;
            return result;
        }

        private string GetParameter(IFormCollection formCollection)
        {
            formCollection.TryGetValue("parameter", out StringValues values);
            return values.FirstOrDefault()?.ToString();
        }

    }
}